package com.up.vms.domain.vm.service;

import com.up.vms.domain.module.BannerDTO;
import com.up.vms.domain.vm.entity.Banner;
import com.up.vms.domain.vm.enums.BannerStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.up.vms.domain.vm.repository.BannerRepository;

import java.util.Optional;

@Service
public class BannerService {

    @Autowired
    private BannerRepository bannerRepository;

    public Page<Banner> findAllByBannerName(BannerDTO bannerDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "created");
        Pageable pageable = PageRequest.of(bannerDTO.getPage(), bannerDTO.getSize(), sort);

        return bannerRepository.findAllByBannerNameLike("%" + bannerDTO.getBannerName() + "%", pageable);
    }

    public Page<Banner> findAllByStatus(BannerDTO bannerDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "sorting");
        Pageable pageable = PageRequest.of(bannerDTO.getPage(), bannerDTO.getSize(), sort);

        return bannerRepository.findAllByStatus(BannerStatus.AVAILABLE.code, pageable);
    }

    public Page<Banner> findAllByPageable(BannerDTO bannerDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "created");
        Pageable pageable = PageRequest.of(bannerDTO.getPage(), bannerDTO.getSize(), sort);

        return bannerRepository.findAll(pageable);
    }

    public Banner findBannerByBannerId(Long bannerId) {

        Optional<Banner> optional = bannerRepository.findById(bannerId);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    public Banner save(Banner saveBanner) {
        Banner newBanner = bannerRepository.save(saveBanner);
        return newBanner;
    }

    public void delete(Banner banner) {
        bannerRepository.delete(banner);
    }
}
